#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import subprocess
import sys

# 设置环境变量以抑制Rust警告
os.environ["RUSTFLAGS"] = "-Awarnings"

# 定义颜色代码
YELLOW = "\033[93m"
RESET = "\033[0m"


def run_all_examples():
    # 自动获取examples文件夹下的所有目录
    examples_path = ".\\examples"
    directories = []

    if os.path.exists(examples_path):
        for item in os.listdir(examples_path):
            item_path = os.path.join(examples_path, item)
            if os.path.isdir(item_path):
                directories.append(item)
        # 按目录名排序
        directories.sort()
    else:
        print(f"错误: 目录 {examples_path} 不存在")
        return

    # 检查命令行参数
    selected_directories = []
    filter_errors = False  # 是否过滤错误输出

    i = 1
    while i < len(sys.argv):
        arg = sys.argv[i]
        if arg == "-e":
            filter_errors = True
            i += 1
        else:
            # 处理目录编号参数
            try:
                dir_num = int(arg)
                if 1 <= dir_num <= len(directories):
                    selected_directories.append(directories[dir_num - 1])
                    print(f"已选择目录: {directories[dir_num - 1]}")
                else:
                    print(
                        f"警告: 目录编号 {dir_num} 超出范围 (1-{len(directories)})，跳过..."
                    )
            except ValueError:
                print(f"警告: 无效的目录编号 '{arg}'，请输入数字，跳过...")
            i += 1

    if not selected_directories:
        # 没有指定目录，运行所有目录
        selected_directories = directories
        print("运行所有墨言示例...")

    if filter_errors:
        print("已启用错误过滤模式，只显示包含'错误'的输出")

    print()

    # 遍历选定的目录并运行其中的墨言文件
    for directory in selected_directories:
        dir_path = os.path.join(".\\examples", directory)
        if os.path.exists(dir_path):
            print(f"正在处理目录: {directory}")
            os.chdir(dir_path)

            # 获取所有.墨言文件
            for file in os.listdir("."):
                if file.endswith(".墨言") or file.endswith(".moyan"):
                    print("=" * 40)
                    print(f"运行: {directory}\\{file}")
                    print("=" * 40)

                    # 运行cargo命令
                    if filter_errors:
                        # 错误过滤模式：捕获输出并检查是否包含"错误"
                        result = subprocess.run(
                            [
                                "cargo",
                                "run",
                                "--quiet",
                                "--release",
                                "--",
                                "-s",
                                file,
                            ],
                            capture_output=True,
                            text=True,
                            encoding="utf-8",
                            errors="ignore",
                        )

                        # 检查输出中是否包含"错误"
                        stdout = result.stdout if result.stdout is not None else ""
                        stderr = result.stderr if result.stderr is not None else ""
                        output = stdout + stderr
                        if "错误" in output:
                            print(output)
                            print()
                            print(YELLOW + "*" * 40 + RESET)
                            print()
                    else:
                        # 正常模式：直接显示输出
                        result = subprocess.run(
                            [
                                "cargo",
                                "run",
                                "--quiet",
                                "--release",
                                "--",
                                "-s",
                                file,
                            ],
                            capture_output=False,
                            text=True,
                        )

                        print()
                        print(YELLOW + "*" * 40 + RESET)
                        print()

            # 返回到项目根目录
            os.chdir("..\\..")
        else:
            print(f"警告: 目录 {dir_path} 不存在，跳过...")
            print()

    print("所有示例运行完成！")


def print_usage():
    print("用法: python run_all_examples.py [选项] [目录编号...]")
    print("选项:")
    print("  -e                         只显示包含'错误'的输出")
    print("示例:")
    print("  python run_all_examples.py              # 运行所有目录")
    print("  python run_all_examples.py 1            # 只运行第一个目录")
    print("  python run_all_examples.py 1 3 5        # 运行第1、3、5个目录")
    print("  python run_all_examples.py -e            # 运行所有目录，只显示错误输出")
    print(
        "  python run_all_examples.py -e 1 3       # 运行第1、3个目录，只显示错误输出"
    )
    print()
    print("可用目录:")

    # 获取examples文件夹下的所有目录
    examples_path = ".\\examples"
    directories = []

    if os.path.exists(examples_path):
        for item in os.listdir(examples_path):
            item_path = os.path.join(examples_path, item)
            if os.path.isdir(item_path):
                directories.append(item)
        # 按目录名排序
        directories.sort()

        for i, dir in enumerate(directories, 1):
            print(f"  {i}: {dir}")
    else:
        print(f"错误: 目录 {examples_path} 不存在")


if __name__ == "__main__":
    if len(sys.argv) > 1 and sys.argv[1] in ["-h", "--help", "help"]:
        print_usage()
    else:
        run_all_examples()
